import { ChangeEvent, Fragment, useEffect, useRef, useState } from 'react';
import './../HomePage.scss'
import { Image, Dropdown, MenuProps, Breadcrumb, Modal, Button, Tooltip, Table, Space } from 'antd';
import { FolderAddOutlined, FileAddOutlined, PlusOutlined, ClockCircleOutlined, FileOutlined, FileMarkdownOutlined, UnorderedListOutlined, ExclamationCircleOutlined, DeleteOutlined, InfoCircleFilled, InfoCircleOutlined, FolderOpenOutlined, FolderViewOutlined, RightSquareOutlined } from '@ant-design/icons'
import AddFolderModal from '../modal/AddFolderModal';
import UploadShareFileModal from './../modal/UploadShareFileModal';
import LoadingWapper from '../../../components/loading/LoadingWapper';
import systemApi from '../../../api/system';
import ShareFileItem from './ShareFileItem';
import { commonSuccessMsg, deepCopy, getChangeEventValue, getFileType, isEmpty, toastShort, findFolderPath, handleDownloadByName, getSingleTdTableHeight, getAZindex, formatTime, addKeyToList, tree2List } from '../../../utils';
import DataInfoDrawer from '../modal/FileInfoDrawer';
import { FileItem } from '../../../utils/types';
import FilePreviewModal from '../modal/FilePreviewModal';
import { useNavigate, useSearchParams } from 'react-router-dom';
import EmptyWapper from '../../../components/loading/EmptyWapper';
import { commonErrorMsg } from '../../../utils';
import useReSize from '../../../hooks/useResize';
import { ColumnsType } from 'antd/es/table';
import Pinyin from '../../../utils/pinyin';
import { TableRowSelection } from 'antd/lib/table/interface';
import { FolderConversion } from '@icon-park/react';
import SelectParentFolderModal from './modal/SelectParentFolderModal';

const ShareFiles = () => {
    const navigate = useNavigate();
    const [searchParams, setSearchParams] = useSearchParams();

    const [loading, setLoading] = useState(true);
    const [queryParams, setQueryParams] = useState<{ name: string }>({ name: "" });

    const [fileList, setFileList] = useState<FileItem[]>([]);
    const [allFileList, setAllFileList] = useState<FileItem[]>([]);
    //文件夹路径
    const [folderList, setFolderList] = useState<FileItem[]>([]);
    //当前聚焦的文件
    const [currentFocusFileItem, setCurrentFocusFileItem] = useState<FileItem>(null);
    const [imagePreviewVisible, setImagePreviewVisible] = useState<boolean>(false);
    const [currentParentFolderId] = useState('');
    const [queryFileName, setQueryFileName] = useState('');
    const [currentSortType, setCurrentSortType] = useState<'1' | '2' | '3' | '4'>('1');
    const [selectedRows, setSelectedRows] = useState<FileItem[]>([]);

    //@ts-ignore
    const [layoutType, setLayoutType] = useState<'card' | 'list'>(searchParams.get('layout') ? searchParams.get('layout') : 'card');

    const addFolderModalRef = useRef<any>(null);
    const dataInfoDrawerRef = useRef<any>(null);
    const filePreviewModalRef = useRef<any>(null);
    const delayTimer = useRef<any>(null);
    const tempFileItem = useRef(null);
    const [deleteLoading, setDeleteLoading] = useState(false);

    const tableContainerRef = useRef<any>(null);
    const tableContainerSize = useReSize(tableContainerRef)

    const handleAddFolder = () => {
        addFolderModalRef.current.openModal();
    };

    const uploadShareFileModalRef = useRef(null);
    const selectParentFolderModalRef = useRef(null);

    useEffect(() => {
        queryShareFileList();
    }, [queryParams, searchParams])

    useEffect(() => {
        const _folderList = findFolderPath(allFileList, searchParams.get('pfid'));
        console.log("folderList--->", _folderList);
        const _sortType = searchParams.get('sort-type');
        setFolderList(_folderList);
        //@ts-ignore
        setCurrentSortType(_sortType);
        // const _layoutType  = searchParams.get('layout');
        // //@ts-ignore
        // setLayoutType(_layoutType ? _layoutType : 'card');
    }, [searchParams, allFileList])

    const queryShareFileList = () => {
        const allParams = {
            page: 1,
            size: 9999,
        }
        let params = {
            page: 1,
            size: 9999,
            params: {
                parentFolderId: "641bced071638dec22cc66d1"
            }
        }
        const parentFolderId = searchParams.get('pfid');
        if (!isEmpty(parentFolderId)) {
            //@ts-ignore
            params.params.parentFolderId = parentFolderId;
        }
        if (!isEmpty(queryFileName)) {
            //@ts-ignore
            params.params.name = queryFileName;
        }
        const _sortType = searchParams.get('sort-type');
        if (!isEmpty(_sortType)) {
            //@ts-ignore
            params.sortType = _sortType;
        }
        setLoading(true)
        Promise.all([systemApi.queryShareFileList(allParams), systemApi.queryShareFileList(params)])
            .then(resList => {
                // console.log("这是所有共享文件----->", resList[0])
                // console.log("这是当前共享文件----->", resList[1])
                setLoading(false);
                setAllFileList(addKeyToList(resList[0].data.list));
                setFileList(addKeyToList(resList[1].data.list));
                setCurrentFocusFileItem(null);
            })
            .catch(err => {
                setLoading(false)
            })
    }

    const handleOpenFileUploadModal = () => {
        uploadShareFileModalRef.current.openModal();
    }

    const _onFinish = () => {
        toastShort('success', commonSuccessMsg);
        queryShareFileList();
    }

    const onClickItem = (fileItem: FileItem) => {
        if (currentFocusFileItem && fileItem.id == currentFocusFileItem.id) {
            setCurrentFocusFileItem(null);
            dataInfoDrawerRef.current.closeDrawer();
        } else {
            setCurrentFocusFileItem(fileItem);
            dataInfoDrawerRef.current.openDrawer(fileItem);
        }
    }

    const handleSearch = () => {
        setQueryParams(deepCopy(queryParams))
    }

    const onDoubleClickItem = (fileItem: FileItem) => {
        setCurrentFocusFileItem(fileItem);
        delayTimer.current = setTimeout(() => {
            if (fileItem.type == 1) {
                //进入下一级文件夹
                console.log("进入下一级文件夹");
                const findExistParentFolderId = '';
                handleSetSearchParams('pfid', fileItem.id);
                setFolderList([...folderList, fileItem]);
                setLoading(true)
                // handleSearch();
                //如果有存在的
            } else {
                //打开预览，如果支持
                const fileType = getFileType(fileItem.path);
                const canPreViewFileTypeList = [];
                // const canPreViewFileTypeList = ['.doc', '.docx', '.xlx', '.xlsx', '.pdf'];
                const imageTypeList = ['.png', '.jpg', '.jpeg'];
                // alert(fileType)
                console.log("imageTypeList", imageTypeList, fileType, imageTypeList.includes(fileType))
                if (canPreViewFileTypeList.includes(fileType)) {
                    filePreviewModalRef.current.openModal(fileItem.url)
                } else if (imageTypeList.includes(fileType)) {
                    setImagePreviewVisible(true)
                } else {
                    toastShort('warning', '该文档不支持预览')
                }
            }
        }, 100);
    }

    const sortMenuList: MenuProps['items'] = [
        {
            key: '1',
            label: '创建时间',
            icon: <ClockCircleOutlined />
        },
        {
            key: '2',
            label: '更新时间',
            icon: <ClockCircleOutlined />
        },
        {
            key: '3',
            label: '文件名称',
            icon: <FileOutlined />
        },
        {
            key: '4',
            label: '文件类型',
            icon: <FileMarkdownOutlined />
        },
    ]

    const adaptSortTypeName = () => {
        try {
            const findSortMenuItem = sortMenuList.find(ele => {
                return ele.key == currentSortType;
            })
            //@ts-ignore
            return findSortMenuItem.label;
        } catch (e) {
            return '创建时间'
        }
    }

    const onClickSortItem: MenuProps['onClick'] = ({ key }) => {
        //@ts-ignore
        setCurrentSortType(key);
        handleSetSearchParams('sort-type', key);
    }

    const onQueryFileNameTextChange = (e: ChangeEvent<HTMLInputElement>) => {
        setQueryFileName(getChangeEventValue(e));
        if (isEmpty(getChangeEventValue(e))) {
            handleSearch();
        }
    }

    const switchLayoutType = () => {
        let newLayoutType = layoutType == 'card' ? 'list' : 'card';
        handleSetSearchParams('layout', newLayoutType);
        //@ts-ignore
        setLayoutType(newLayoutType)
    }

    const generateFolderPath = () => {
        let items = [{
            name: "共享文档",
            id: "641bced071638dec22cc66d1"
        }];
        folderList.forEach((folder, folderIndex) => {
            items.push(folder)
        })
        return items;
    }

    const handleSetSearchParams = (key: string, value: string) => {
        let newParams = new URLSearchParams(searchParams.toString());
        newParams.set(key, value);
        setSearchParams(newParams);
    }

    const onClickItemFolderPath = (e, fileItem: FileItem) => {
        e.preventDefault();
        e.stopPropagation();
        handleSetSearchParams('pfid', fileItem.id);
    }

    const renderFolerPath = (item) => {
        const pfid = searchParams.get('pfid');
        return (
            <div
                className='folder-switch-item'
                onClick={(e) => onClickItemFolderPath(e, item)}
                style={{ color: pfid == item.id ? '#262626' : '#8c8c8c' }}
            >
                {item.name}
            </div>
        )
    }

    const _onReNameFile = (fileItem: FileItem) => {
        addFolderModalRef.current.openModal(fileItem);
        dataInfoDrawerRef.current.closeDrawer();

    }

    const _onPreViewFile = (fileItem: FileItem) => {
        filePreviewModalRef.current.openModal(fileItem.url);
        dataInfoDrawerRef.current.closeDrawer();
    }

    const _onDownLoadFile = (fileItem: FileItem) => {
        handleDownloadByName(fileItem.url, fileItem.name, true)
        dataInfoDrawerRef.current.closeDrawer();
    }

    const _onChangeParentFolder = (fileItem: FileItem) => {
        openParentFolderSelectModal(fileItem);
    }

    const [modal, contextHolder] = Modal.useModal();

    const _onDeleteFile = (fileItem: FileItem) => {
        modal.confirm({
            title: '温馨提示',
            icon: <ExclamationCircleOutlined />,
            content: '确认删除此文件？',
            okText: '确认',
            cancelText: '取消',
            centered: true,
            onOk: confirmToDeleteShareFile,
            okButtonProps: { loading: deleteLoading }
        });
        tempFileItem.current = fileItem;
    }

    const confirmToDeleteShareFile = () => {
        let params = tempFileItem.current;
        params.isDeleted = true;
        setDeleteLoading(true);
        dataInfoDrawerRef.current.closeDrawer();
        systemApi.createOrUpdateShareFolder(params)
            .then(res => {
                console.log("res---->", res)
                _onFinish();
                setDeleteLoading(false);
            })
            .catch(err => {
                toastShort('error', commonErrorMsg)
                setDeleteLoading(false);
            })
    }

    const deleteShareFileMutiple = () => {
        if(layoutType == 'card'){
            return toastShort('warning', '请切换到列表模式后勾选需要删除的文件/文件夹')
        }
        if (selectedRows.length == 0) {
            return toastShort('error', '请先勾选所需删除的文件/文件夹')
        }
        modal.confirm({
            title: '温馨提示',
            icon: <ExclamationCircleOutlined />,
            content: '确认删除所选的共享文件？',
            okText: '确认',
            cancelText: '取消',
            centered: true,
            onOk: confirmToDeleteShareFileMutiple,
            okButtonProps: { loading: deleteLoading }
        });
    }

    const confirmToDeleteShareFileMutiple = () => {
        let rowIdList = [];
        selectedRows.forEach(row => {
            rowIdList.push(row.id)
        })
        let params = {
            ids: rowIdList
        };
        systemApi.deleteShareFileMutiple(params)
            .then(res => {
                console.log("res---->", res)
                _onFinish();
                setDeleteLoading(false);
            })
            .catch(err => {
                toastShort('error', commonErrorMsg)
                setDeleteLoading(false);
            })
    }

    const onTableChange = (pagination, filters, sorter, extra) => {
        console.log("onTableChange--->", sorter)
    }


    const renderFileIconMini = (item: FileItem) => {
        if (item.type == 1) {
            return (
                <img className='folder-icon-img-mini' src={require("./../../../assets/image/folder.png")} alt="" />
            )
        } else {
            const fileType = getFileType(item.path);
            // console.log("fileType--->", fileType)
            switch (fileType.toLowerCase()) {
                case '.png':
                case '.jpg':
                case '.jpeg':
                    return (
                        <img
                            className='file-icon-img-mini'
                            src={item && item.url}
                        />
                    )
                    break;
                case '.doc':
                case '.docx':
                    return (
                        <img className='file-icon-img-mini' src={require("./../../../assets/image/word.png")} alt="" />
                    )
                    break;
                case '.xlx':
                case '.xlsx':
                    return (
                        <img className='file-icon-img-mini' src={require("./../../../assets/image/XLS.png")} alt="" />
                    )
                    break;
                case '.ppt':
                case '.pptx':
                    return (
                        <img className='file-icon-img-mini' src={require("./../../../assets/image/PPT.png")} alt="" />
                    )
                    break;
                case '.zip':
                case '.rar':
                    return (
                        <img className='file-icon-img-mini' src={require("./../../../assets/image/zip.png")} alt="" />
                    )
                    break;
                case '.pdf':
                    return (
                        <img className='file-icon-img-mini' src={require("./../../../assets/image/PDF.png")} alt="" />
                    )
                    break;
                default:
                    break;
            }
        }
    }

    const openParentFolderSelectModal = (fileItem: FileItem) => {
        selectParentFolderModalRef.current.openModal(fileItem);
    }

    const columns: ColumnsType<FileItem> = [
        {
            title: '文件名称',
            dataIndex: 'name',
            key: 'name',
            render: (value, record, index) => {
                return (
                    <div className='flex-row'>
                        <div
                            title='编制规划'
                            className='table-file-icon'
                        >
                            {renderFileIconMini(record)}
                        </div>
                        <span>{record.name}</span>
                    </div>
                )
            },
            sorter: {
                compare: (a, b) => getAZindex(Pinyin.getWordsCode(a.name)[0]) > getAZindex(Pinyin.getWordsCode(b.name)[0]) ? 1 : -1.
            },
        },
        {
            title: '创建者',
            key: 'createUserName',
            dataIndex: 'createUserName',
            render: (value, record, index) => {
                return <span style={{ fontWeight: '700' }}>{record.createUserName}</span>
            },
            sorter: {
                compare: (a, b) => getAZindex(Pinyin.getWordsCode(a.createUserName)[0]) > getAZindex(Pinyin.getWordsCode(b.createUserName)[0]) ? 1 : -1,
            },
        },
        {
            title: '创建时间',
            key: 'createDate',
            dataIndex: 'createDate',
            render: (value, record, index) => {
                return <span>{formatTime(record.createDate)}</span>
            },
            sorter: {
                compare: (a, b) => Number(a.createDate) > Number(b.createDate) ? 1 : -1,
            },
        },
        {
            title: '更新时间',
            key: 'updateDate',
            dataIndex: 'updateDate',
            render: (value, record, index) => {
                return <span>{formatTime(record.updateDate)}</span>
            },
            sorter: {
                compare: (a, b) => Number(a.updateDate) > Number(b.updateDate) ? 1 : -1,
            },
        },
        {
            title: '操作',
            key: 'option',
            dataIndex: 'option',
            align: 'center',
            fixed: 'right',
            render: (value, record, index) => {
                return (
                    <Space>
                        {
                            record.type == 1 ?
                                <Tooltip
                                    title={"打开文件夹"}
                                >
                                    <Button
                                        type={'text'}
                                        icon={<FolderOpenOutlined />}
                                        onClick={() => onDoubleClickItem(record)}
                                    />
                                </Tooltip>
                                :
                                <Tooltip
                                    title={"打开预览"}
                                >
                                    <Button
                                        type={'text'}
                                        icon={<FolderViewOutlined />}
                                        onClick={() => onDoubleClickItem(record)}
                                    />
                                </Tooltip>
                        }
                        {
                            record.type == 2 ?
                                <Tooltip
                                    title={"移动文件夹"}
                                >
                                    <Button
                                        type={'text'}
                                        icon={(
                                            <div>
                                                <div style={{ marginBottom: -5 }}>
                                                    <FolderConversion
                                                        theme="outline"
                                                        size="16"
                                                        fill="#333"
                                                    />
                                                </div>
                                            </div>
                                        )}
                                        onClick={() => openParentFolderSelectModal(record)}
                                    />
                                </Tooltip>
                                :
                                null
                        }
                        <Tooltip
                            title={"基本信息"}
                        >
                            <Button
                                type={'text'}
                                icon={<InfoCircleOutlined />}
                                onClick={() => onClickItem(record)}
                            />
                        </Tooltip>
                    </Space>
                )
            }
        },
    ];

    const rowSelection: TableRowSelection<FileItem> = {
        onChange: (selectedRowKeys, selectedRows) => {
        },
        onSelect: (record, selected, selectedRows) => {
            // console.log(record, selected, selectedRows);
            setSelectedRows(selectedRows);
        },
        onSelectAll: (selected, selectedRows, changeRows) => {
            // console.log(selected, selectedRows, changeRows);
        },
    };

    return (
        <div
            style={{ position: 'relative' }}
            className='flex-col side-bar-content'
        >
            <div className='flex-row side-bar-content-top'>
                <div className='flex-row side-bar-content-top-switch'>
                    <Breadcrumb
                        //@ts-ignore
                        items={generateFolderPath()}
                        itemRender={renderFolerPath}
                    />
                </div>
                <div className='flex-row side-bar-content-top-right'>
                    <div className='flex-row search-box'>
                        <input
                            className='search-box-input'
                            placeholder='搜索文件夹/文档名称'
                            value={queryFileName}
                            onChange={onQueryFileNameTextChange}
                            maxLength={10}
                        />
                        <div
                            className='flex-row search-box-btn'
                            onClick={handleSearch}
                        >
                            <i
                                style={{ fontSize: '14px' }}
                                className='iconfont-1 ghzs-gray-sousuo'
                            />
                            <p>查询</p>
                        </div>
                    </div>
                    <Tooltip
                        title="排序方式"
                    >
                        <Dropdown
                            menu={{
                                items: sortMenuList,
                                onClick: onClickSortItem
                            }}
                            placement="bottom"
                            arrow={{ pointAtCenter: true }}
                            trigger={['click']}
                        >
                            <div className='flex-row side-bar-content-top-right-item'>
                                <p>{adaptSortTypeName()}</p>
                                <i style={{ fontSize: '12px' }} className='iconfont-1 ghzs-gray-xiala' />
                            </div>
                        </Dropdown>
                    </Tooltip>
                    <Tooltip
                        title="切换卡片/列表展示"
                    >
                        <Button
                            icon={layoutType == 'card' ? <i style={{ fontSize: '18px' }} className='iconfont-1 ghzs-gray-qiapianxingshi' /> : <UnorderedListOutlined />}
                            type={'text'}
                            onClick={switchLayoutType}
                            className='side-bar-content-top-right-item'
                            style={{ marginRight: 10 }}
                        />
                    </Tooltip>
                    <Tooltip
                        title="删除所选的文件"
                    >
                        <Button
                            icon={<DeleteOutlined />}
                            type={'text'}
                            onClick={deleteShareFileMutiple}
                            danger
                        />
                    </Tooltip>
                </div>
            </div>
            <div className='side-bar-content-scroll share-files-scroll'>
                <div className='flex-row side-bar-content-header'>
                    <div className='flex-row side-bar-content-header-left'>
                        <div
                            className='flex-row add-file-btn'
                            onClick={handleAddFolder}
                        >
                            <div className='flex-row add-file-btn-left'>
                                {/* <FolderAddOutlined style={{ fontSize: '26px', color: '#0f6432' }} /> */}
                                <img src={require('./../../../assets/image/file-add-icon.png')} style={{width: 24}}/>
                                <div className='flex-col add-file-btn-content'>
                                    <p className='add-file-btn-name'>创建文件夹</p>
                                    <p className='add-file-btn-desc'>为文件设置分组</p>
                                </div>
                            </div>
                            <PlusOutlined style={{ fontSize: '14px' }} />
                        </div>
                    </div>
                    <div className='flex-row side-bar-content-header-left'>
                        <div
                            className='flex-row add-file-btn'
                            onClick={handleOpenFileUploadModal}
                        >
                            <div className='flex-row add-file-btn-left'>
                                {/* <FileAddOutlined style={{ fontSize: '26px', color: '#0f6432' }} /> */}
                                <img src={require('./../../../assets/image/file-upload-icon.png')} style={{width: 24}}/>
                                <div className='flex-col add-file-btn-content'>
                                    <p className='add-file-btn-name'>上传文件</p>
                                    <p className='add-file-btn-desc' style={{ paddingLeft: 1 }}>图片、表格、文稿、压缩包等</p>
                                </div>
                            </div>
                            <PlusOutlined style={{ fontSize: '14px' }} />
                        </div>
                    </div>
                    <div className='flex-row side-bar-content-header-right'>
                    </div>
                </div>
                <div
                    ref={tableContainerRef}
                    className='folder-list-content'
                    style={{
                        height: 'calc(100vh - 280px)',
                        width: '100%',
                    }}
                >
                    {
                        layoutType == 'card' ?
                            <Fragment>
                                {
                                    fileList && fileList.map((file, fileIndex) => {
                                        return (
                                            <ShareFileItem
                                                item={file}
                                                layoutType={layoutType}
                                                key={fileIndex + ''}
                                                onClickItem={onClickItem}
                                                currentFocusFileItem={currentFocusFileItem}
                                                onDoubleClickItem={onDoubleClickItem}
                                            />
                                        )
                                    })
                                }
                                {
                                    fileList.length == 0 && !loading ?
                                        <EmptyWapper />
                                        :
                                        null
                                }
                                {
                                    loading ?
                                        <LoadingWapper />
                                        :
                                        null
                                }
                            </Fragment>
                            :
                            <Table
                                rowSelection={{
                                    type: 'checkbox',
                                    ...rowSelection
                                }}
                                columns={columns}
                                dataSource={fileList}
                                onChange={onTableChange}
                                style={{ width: '100%' }}
                                pagination={false}
                                loading={loading}
                                scroll={{ x: 'max-content', y: getSingleTdTableHeight(tableContainerSize.height) }}
                            />
                    }
                </div>
            </div>
            <AddFolderModal
                ref={addFolderModalRef}
                onFinish={_onFinish}
            />
            <UploadShareFileModal
                ref={uploadShareFileModalRef}
                onFinish={_onFinish}
            />
            <DataInfoDrawer
                ref={dataInfoDrawerRef}
                onReNameFile={_onReNameFile}
                onPreViewFile={_onPreViewFile}
                onDownLoadFile={_onDownLoadFile}
                onChangeParentFolder={_onChangeParentFolder}
                onDeleteFile={_onDeleteFile}
            />
            <FilePreviewModal
                ref={filePreviewModalRef}
            />
            {
                currentFocusFileItem && currentFocusFileItem.url ?
                    <Image
                        width={120}
                        style={{ display: 'none' }}
                        src={currentFocusFileItem.url}
                        preview={{
                            visible: imagePreviewVisible,
                            scaleStep: 0.4,
                            // width: 600,
                            src: currentFocusFileItem && currentFocusFileItem.url ? currentFocusFileItem.url : '',
                            onVisibleChange: (value) => {
                                setImagePreviewVisible(value);
                            },
                        }}
                    />
                    :
                    null
            }
            {contextHolder}
            <SelectParentFolderModal
                ref={selectParentFolderModalRef}
                onFinish={_onFinish}
            />
        </div>
    )
}

export default ShareFiles;